package com.botarena.server.servlets.http;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;

import com.botarena.server.errors.BotArenaException;
import com.botarena.server.helper.Upload;
import com.botarena.server.model.Account;
import com.botarena.server.model.Bot;
import com.botarena.server.services.AccountService;
import com.botarena.server.services.BotService;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class CreateBotServlet extends HttpServlet {

	private static final long serialVersionUID = 2947991631037962748L;
	
	private static final Logger log = Logger.getLogger(CreateBotServlet.class.getName());

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		BotService botService = new BotService();
		AccountService accountService = new AccountService();
		
		try {
			Upload form = new Upload(request);
			Bot bot = new Bot();
			
			bot.setName(form.getField("name"));
			bot.setParameters(form.getField("parameters"));
			bot.setContestant("on".equals(form.getField("contestant")));
			Key contestKey = KeyFactory.stringToKey(form.getField("contestKey"));
			
			String sourceCode = form.getFileContent("uploadFormElement");
			
			log.info("Got source: " + sourceCode);
			
			bot.setSourceCode(sourceCode);
			
			Account account = accountService.getAccount(accountService.getGoogleUser());
			
			if (!botService.canUserAddBot(account)) {
				throw new BotArenaException("Too many bots! Maximum is " + AccountService.MAX_NUMBER_OF_BOTS);
			}
			
			if (botService.isNameAvailable(bot)) {
				throw new BotArenaException("A bot with name: " + bot.getName() + " already exists.");
			}
			
			// TODO do it outside request processing
			botService.compile(bot);

			
			if (bot.getCompilationResults().equals("OK")) {
				botService.create(bot, account.getKey(), contestKey);
				String key = "key: " + KeyFactory.keyToString(bot.getKey());
				response.setContentType("text/plain");
				response.getOutputStream().write(key.getBytes());
			} else {
				String error = "Compilation errors: \n" + bot.getCompilationResults();
				response.getOutputStream().write(error.getBytes());
			}
			
		} catch (BotArenaException e) {
			String error = "Cannot create bot: " + e.getMessage();
			response.getOutputStream().write(error.getBytes());
		} catch (FileUploadException e) {
			String error = "Cannot upload bot: " + e.getMessage();
			response.getOutputStream().write(error.getBytes());
		} finally {
			response.getOutputStream().close();
		}
	}

}